<?php

/**
 * 文档服务
 * @author yuzy 2015-5-7
 */

namespace common\services\myhtsq;

use common\models\myhtsq\ContractDocumentModel;
use common\models\myhtsq\DocumentModel;
use common\repositories\myhtsq\ContractDocumentRepository;
use common\repositories\myhtsq\ContractManageRepository;
use common\services\BaseService;
use common\error\ErrorCode;
use common\repositories\myhtsq\DocumentRepository;
use common\support\StringHelper;
use PHPExcel_IOFactory;

class DocumentService extends BaseService {

    /**
     * 构造函数
     */
    public function __construct() {
        
    }

    /**
     * 文档列表
     * @param string $businessId 业务id
     * @return array
     */
    public static function getDocumentListByBusinessId($businessId) {
        return DocumentRepository::getDocumentListByBusinessId($businessId);
    }	

    /**
     * 新增文档
     * @param \common\models\myhtsq\DocumentModel $documentModel
     * @return boolean|string 失败返回false，成功返回新增的文档Id
     */
    public function addDocument($documentModel) {
        if ($documentModel->validate()) {
            $newdoc = new DocumentRepository();
            $result = $newdoc->addDocument($documentModel);
            if ($result === FALSE) {
                return $this->setAndReturn($this->getErrCode());
            } else {
                return $result;
            }
        } else {
            return $this->setAndReturn(ErrorCode::ERR_DOCUMENT_FORM_VERIFY_FAIL);
        }
    }    
    
    public static function delDocumentById($docmentId){
        return DocumentRepository::delDocumentById($docmentId);
    }

    public static function delDocumentByBusinessId($businessId){
        return DocumentRepository::delDocumentByBusinessId($businessId);
    }

    public function downloadContractDocStoreTemplate(){
        $outName = '纸质合同存放信息导入模板';
        $ext = 'xlsx';
        $file = dirname(\Yii::$app->basePath) . "/files/upload/excel/{$outName}.{$ext}";
        $fp = fopen($file, "rb");
        header("Expires: 0");
        header("Content-Type: xlsx");
        header("Content-Disposition: attachment; filename={$outName}.{$ext}");
        fpassthru($fp);
        exit();
    }

    /**
     * 导入纸质合同存放信息
     * @param $filePath
     * @param $ext
     * @return string
     * @throws \PHPExcel_Exception
     * @throws \PHPExcel_Reader_Exception
     */
    public function importContractDocStore($filePath, $ext)
    {
        ini_set('max_execution_time', 5 * 60);    //超时设置5分钟
        if ($ext == 'xlsx') {
            $readerType = 'Excel2007';
        } else {
            $readerType = 'Excel5';
        }
        $reader = PHPExcel_IOFactory::createReader($readerType); //设置以Excel5格式(Excel97-2003工作簿)
        $PHPExcel = $reader->load($filePath); // 载入excel
        $sheet = $PHPExcel->getSheet(0); // 读取第一個工作表
        $highestRow = $sheet->getHighestRow(); // 取得总行数
        $highestColumn = $sheet->getHighestColumn(); // 取得总列数

        //循环读取每个单元格的数据
        $disableRows = 1;  //不需要处理的行数，第1行不需要处理
        $k = 0;
        $errorRow = [];

        //导入字段
        //合同所属区域	客户简称	签约客户全称	签约人	合同编号	签约金额	录入日期	文件类型	文档类型(原件或复印件) 纸质合同归档日期	纸质合同存放位置	保管人	所属文件夹名称
        for ($row = 1 + $disableRows; $row <= $highestRow; $row++) {   //行数是以第2行开始

            $rowValueData = [];
            for ($column = 'A'; $column <= $highestColumn; $column++) { //列数是以A列开始
                $value = trim($sheet->getCell($column . $row)->getValue());
                $rowValueData[] = $value;  //得到一行数据
            }
            $k++;
//            $rowValueData[9] = date('Y-m-d', \PHPExcel_Shared_Date::ExcelToPHP($rowValueData[9]));  //日期格式特别处理
            $afterData = $this->processImportData($rowValueData);
            if (in_array(null, $afterData, true)) {
                $errorRow[] = $k;
                continue;
            }
            $contractDocument = new ContractDocumentModel();
            $contractDocument->setScenario('add');
            $contractDocument->load($afterData, '');
            if ($contractDocument->validate()) {
                ContractDocumentRepository::addContractDocument($contractDocument); // 新增合同文档信息
            }
            $invoiceModel = null;
        }

        $errorCount = count($errorRow);
        $successCount = $k - $errorCount;
        $result = "成功导入{$successCount}条，失败{$errorCount}条";
        if ($errorCount > 0) {
            $result .= ',其中第' . implode('、', $errorRow) . '行数据有误';
        }
        return $result;
    }

    /**
     * 处理导入前的数据
     * @param $rowData
     * @return array
     */
    protected function processImportData($rowData)
    {
        $contract_id = ContractManageRepository::getContractInfoByContractCode(trim($rowData[1]),'contract_id');
        $result = [
            'pigeonhole_date' => $rowData[5],   //纸质合同归档日期
            'keeper' => ErpInterfaceService::getUserIdByName($rowData[10]),  //保管人id
            'document_ext_name' => '合同', //文件类型
            'document_type' => $rowData[2], //文档类型
            'document_path' => $rowData[3], //纸质合同存放位置
            'document_dir' => $rowData[4],  //纸质合同存放位置
            'created_on' => date('Y-m-d H:i:s'),
            'modified_on' => date('Y-m-d H:i:s'),
            'created_by' => 'system',
            'modified_by' => 'system',
            'contract_id' => $contract_id['contract_id']
        ];
        return $result;
    }
    
}
